<template>
	<view class="my-content">
		<view class="form-box">
			<text class="form-title">*车位照片</text>
			<view class="ava-img" @click="uploadImage('pic')">
				<image :src="formData.pic" mode="widthFix" v-if="formData.pic"></image>
				<text v-else>+</text>
			</view>
		</view>
		<view class="form-box">
			<text class="form-title">*车位名称</text>
			<view class="form-item">
				<input type="text" placeholder="请输入车位名称" v-model="formData.name" />
			</view>
			<text class="form-title mt20">*车位编号</text>
			<view class="form-item">
				<input type="text" placeholder="请输入车位编号" v-model="formData.sn" />
			</view>
			<text style="display: none;" class="form-title mt20">*请选择地图标点</text>
			<view style="display: none;" class="form-item" @click="showMapDialog = true">
				<text class="blue">{{ formData.lat && formData.lng ? '已选择位置' : '请选择地图标点' }}</text>
			</view>
			<view style="display: none;" class="form-item" v-if="formData.lat||formData.lng">
				<input type="text" style="font-size: 14px;" placeholder="请输入纬度" v-model="formData.lat" />
				<input type="text" style="font-size: 14px;" placeholder="请输入经度" v-model="formData.lng" />
				<input type="text" style="display: none;" v-model="markers[0]['title']" />
				<input type="text" style="font-size: 14px;" v-model="markers[0]['address']" />
			</view>
			<view class="popup-mask" v-if="showMapDialog" @click="closeMap">
				<view class="popup-content" @click.stop>
					<view class="map-dialog">
						<view class="dialog-header">
							<text class="title">选择位置</text>
							<text class="close" @click="closeMap">×</text>
						</view>
						<map class="map" :latitude="mapCenter.latitude" :longitude="mapCenter.longitude"
							:markers="markers" @regionchange="onMapChange">
						</map>
						<view class="dialog-footer">
							<button class="btn cancel-btn" @click="closeMap">取消</button>
							<button class="btn confirm-btn" @click="confirmLocation">确认位置</button>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="form-box">
			<text class="form-title">*车位位置示意图照片</text>
			<view class="img-list">
				<view class="img-add" @click="uploadImage('images')" v-if="formData.images.length < 4">
					<text>+</text>
				</view>
				<view class="img-item" style="position: relative;" v-for="(item, index) in formData.images"
					:key="index">
					<div class="w-30 h-30 bg-red rounded-full" style="position: absolute;top: 0;right: 0;z-index: 9;">
						<image @click="formData.images = formData.images.filter(i => i != item)"
							src="/static/icon/close.png" class="w-30 h-30" mode="widthFix"></image>
					</div>
					<image :src="item" mode="widthFix"></image>
				</view>
			</view>
			<text class="num-box">{{ formData.images.length }}/4</text>
		</view>
		<view class="form-box" style="position: relative;">
			<view style="color: blue; text-align: right;position: absolute;top: 10px;left: 0;width: 95%;" @click="add"> 添加 </view>
			<text class="form-title">*营业开始时间</text>
			<view class="form-item">
				<picker mode="time" :value="formData.start_time" @change="onStartTimeChange">

					<text class="blue">{{ formData.start_time || '请选择营业开始时间' }}</text>
				</picker>
			</view>
		
			<text class="form-title">*营业结束时间</text>
			<view class="form-item">
				<picker mode="time" :value="formData.end_time" @change="onEndTimeChange">
					<text class="blue">{{ formData.end_time || '请选择营业结束时间' }}</text>
				</picker>
			</view>
		</view>
		
		<view class="form-box"  v-show="num>1" style="position: relative;">
			<view style="color: blue; text-align: right;position: absolute;top: 10px;left: 0;width: 95%;" @click="del(2)"> 删除 </view>
			<text class="form-title">*营业开始时间</text>
			<view class="form-item">
				<picker mode="time" :value="formData.start_time2" @change="onStartTimeChange2">
		
					<text class="blue">{{ formData.start_time2 || '请选择营业开始时间' }}</text>
				</picker>
			</view>
		
			<text class="form-title">*营业结束时间</text>
			<view class="form-item">
				<picker mode="time" :value="formData.end_time2" @change="onEndTimeChange2">
					<text class="blue">{{ formData.end_time2 || '请选择营业结束时间' }}</text>
				</picker>
			</view>
		</view>
		
		<view class="form-box"  v-show="num>2" style="position: relative;">
			<view style="color: blue; text-align: right;position: absolute;top: 10px;left: 0;width: 95%;" @click="del(3)"> 删除 </view>
			<text class="form-title">*营业开始时间</text>
			<view class="form-item">
				<picker mode="time" :value="formData.start_time3" @change="onStartTimeChange3">
		
					<text class="blue">{{ formData.start_time3 || '请选择营业开始时间' }}</text>
				</picker>
			</view>
		
			<text class="form-title">*营业结束时间</text>
			<view class="form-item">
				<picker mode="time" :value="formData.end_time3" @change="onEndTimeChange3">
					<text class="blue">{{ formData.end_time3 || '请选择营业结束时间' }}</text>
				</picker>
			</view>
		</view>
		
		<view class="form-box">
			<text class="form-title">*停车费（元/小时）</text>
			<view class="form-item">
				<input type="text" placeholder="请输入停车费" v-model="formData.price" />
			</view>
		</view>
		<view class="form-box">
			<text class="form-title">*停车费说明</text>
			<view class="form-item">
				<textarea v-model="formData.remark" maxlength="60" @input="sumfontnum"
					placeholder="请输入停车费说明"></textarea>
				<text class="font-num">{{ fontNum }}/60</text>
			</view>
		</view>
		<button class="submit" @click="submitForm">确认提交</button>
		<!-- <view class="test-btn" @click="fillTestData">
			一键填充测试数据
		</view> -->
	</view>
</template>

<script>
export default {
	data() {
		return {
			num:1,
			showMapDialog: false,
			userInfo: {},
			formData: {
				pic: '', // 车位头像
				name: '', // 车位名称
				sn: '', // 车位编号
				lat: '', // 纬度
				lng: '', // 经度
				images: [], // 车位详情照片
				start_time: '', // 营业开始时间
				end_time: '', // 营业结束时间
				start_time2: '', // 营业开始时间
				end_time2: '', // 营业结束时间
				start_time3: '', // 营业开始时间
				end_time3: '', // 营业结束时间
				price: '', // 停车费
				remark: '', // 备注
				user_id: '' // 用户id
			},
			mapCenter: {
				latitude: 39.908692,
				longitude: 116.397477
			},
			markers: [{
				id: 1,
				latitude: 39.908692,
				longitude: 116.397477,
				title:'',
				address:'',
				width:30,
				height:30,
				iconPath: '/static/icon/address2.png', // 自定义图标路径，如果需要的话
			}],
			fontNum: 0,
			id:''
		}
	},
	onLoad(options) {
		var that = this
		
		uni.getLocation({
			type: 'wgs84',
			success: (res) => {
				that.markers[0].latitude = res.latitude
				that.markers[0].longitude = res.longitude
				that.mapCenter.latitude = res.latitude
				that.mapCenter.longitude= res.longitude
			},
			fail: (e) => {
				console.log(e)
			}
		})
		if(options.item){
			
			this.formData = JSON.parse(options.item)
			
			this.id = this.formData.id
			if(this.formData){
				this.formData.images = this.formData.images.split(',')
			}
			if(this.formData.start_time2){
				this.num = this.num+1
			}
			if(this.formData.start_time2&&this.formData.start_time3){
				this.num = this.num+1
			}
			
			if((this.formData.lat=='')||(this.formData.lng=='')){
				this.getUserInfo()
			}
		}
		if((this.formData.lat=='')||(this.formData.lng=='')){
			this.getUserInfo()
		}
		
	},
	methods: {
		async getUserInfo() {
			const res = await this.http("get", "/api/user/user_info", {})
			this.userInfo = res.data
			console.log(this.userInfo)
			this.formData.lat = this.userInfo.station.lat
			this.formData.lng = this.userInfo.station.lng
			this.user_id = this.userInfo.id
		},
		add(){
			if(this.num<3){
				this.num = this.num+1
			}else{
				uni.showToast({
					title: '至多可以添加3个哦',
					icon: 'none'
				});
			}
		},
		del(i){
			if(this.num>1){
				this.num = this.num-1
			}
			if(i==2){
				if(this.formData.start_time3){
					this.formData.start_time2 = this.formData.start_time3
					this.formData.end_time2 = this.formData.end_time3
					this.formData.start_time3 = ''
					this.formData.end_time3 = ''
				}else{
					this.formData.start_time2 = ''
					this.formData.end_time2 = ''
				}
			}
			if(i==3){
				this.formData.start_time3 = ''
				this.formData.end_time3 = ''
			}
		},
		sumfontnum(e) {
			this.fontNum = e.detail.value.length
		},

		onStartTimeChange(e) {
			this.formData.start_time = e.detail.value
		},

		onEndTimeChange(e) {
			this.formData.end_time = e.detail.value
		},
		
		onStartTimeChange2(e) {
			this.formData.start_time2 = e.detail.value
		},
		
		onEndTimeChange2(e) {
			this.formData.end_time2 = e.detail.value
		},
		
		onStartTimeChange3(e) {
			this.formData.start_time3 = e.detail.value
		},
		
		onEndTimeChange3(e) {
			this.formData.end_time3 = e.detail.value
		},

		// 表单验证
		validateForm() {
			if (!this.formData.pic) {
				uni.showToast({
					title: '请上传车位照片',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.name) {
				uni.showToast({
					title: '请输入车位名称',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.sn) {
				uni.showToast({
					title: '请输入车位编号',
					icon: 'none'
				});
				return false;
			}
			
			if (this.formData.images.length === 0) {
				uni.showToast({
					title: '请上传车位详情照片',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.start_time) {
				uni.showToast({
					title: '请选择营业开始时间',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.end_time) {
				uni.showToast({
					title: '请选择营业结束时间',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.price) {
				uni.showToast({
					title: '请输入停车费',
					icon: 'none'
				});
				return false;
			}
			
			if (!this.formData.remark) {
				uni.showToast({
					title: '请输入停车费说明',
					icon: 'none'
				});
				return false;
			}
			
			
			return true;
		},

		// 提交表单
		async submitForm() {
			if (!this.validateForm()) {
				return;
			}

			uni.showLoading({
				title: '提交中...'
			});

			try {
				const path = this.id ? '/api/park/update' : '/api/park/add';
				const response = await this.http('post', path, this.formData, true);

				if (response.code === 200) {
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});
					setTimeout(() => {
						 uni.navigateBack();
					}, 1500);
				} else {
					this.toast(response.message);
				}
			} catch (error) {
				console.error('提交失败:', error);
			} finally {
				uni.hideLoading();
			}
		},

		// 上传图片方法
		uploadImage(type) {
			uni.chooseImage({
				count: type === 'images' ? 4 : 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: async (res) => {
					const tempFilePaths = res.tempFilePaths;

					uni.showLoading({
						title: '上传中...'
					});

					try {
						const uploadTasks = tempFilePaths.map(path => {
							return new Promise((resolve, reject) => {
								uni.uploadFile({
									url: 'https://app.yinuoxinnengyuan.cn/index.php/api/index/uploads',
									filePath: path,
									name: 'file',
									success: (uploadRes) => {
										const data = JSON.parse(uploadRes.data);
										resolve(data.data.pic_path);
									},
									fail: reject
								});
							});
						});

						const uploadedUrls = await Promise.all(uploadTasks);

						if (type === 'pic') {
							this.formData.pic = uploadedUrls[0];
						} else if (type === 'images') {
							const newImages = [...this.formData.images, ...uploadedUrls];
							this.formData.images = newImages.slice(0, 4);
						}

						uni.showToast({
							title: '上传成功',
							icon: 'success'
						});
					} catch (error) {
						uni.showToast({
							title: '上传失败',
							icon: 'error'
						});
						console.error('上传失败:', error);
					} finally {
						uni.hideLoading();
					}
				}
			});
		},

		// 地图区域变化时的处理逻辑
		onMapChange(e) {
			console.log(e)
			if (e.type === 'end') {
				this.formData.lat = e.detail.centerLocation.latitude
				this.formData.lng = e.detail.centerLocation.longitude
				this.markers[0].latitude = this.formData.lat
				this.markers[0].longitude = this.formData.lng
				this.mapCenter.latitude = this.formData.lat
				this.mapCenter.longitude = this.formData.lng
				
				this.getAddress(e.detail.centerLocation.latitude, e.detail.centerLocation.longitude);

				

			}
		},
		
		getAddress(latitude, longitude) {
		  // 使用腾讯地图API获取地址名称（示例使用腾讯地图API，你也可以使用高德地图API或其他）
		  const key = 'GKHBZ-RTM3U-Q7WVG-4R3DT-HVAEH-MWFHD'; // 替换为你的API密钥
		  const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}`;
		  var that = this
		  uni.request({
			url: url,
			method: 'GET',
			success: (res) => {
				console.log(res)
			  if ((res.data.status === 0)&&(res.data.message==='Success')) {
				const address = res.data.result.address; // 获取地址信息
				this.markers[0].title = address
				this.markers[0].address = res.data.result.formatted_addresses.recommend
				console.log('地址:', address);
				// 这里可以更新界面或进行其他操作
			  } else {
				console.error('获取地址失败:', res.data.message);
			  }
			},
			fail: (error) => {
			  console.error('请求失败:', error);
			}
		  });
		},

		closeMap() {
			this.showMapDialog = false;
		},

		confirmLocation() {
			this.closeMap();
		},

		// 填充测试数据
		fillTestData() {
			this.formData = {
				pic: 'https://app.yinuoxinnengyuan.cn/uploads/20240320/test.jpg',
				name: '测试车位A区12号',
				sn: 'PARK' + Math.floor(Math.random() * 10000),
				lat: '39.908692',
				lng: '116.397477',
				images: [
					'https://app.yinuoxinnengyuan.cn/uploads/20240320/test1.jpg',
					'https://app.yinuoxinnengyuan.cn/uploads/20240320/test2.jpg'
				],
				start_time: '08:00',
				end_time: '22:00',
				price: '10',
				remark: '测试车位，每小时10元，充电期间免费停车2小时，超时按正常收费。',
				user_id: ''
			}

			this.fontNum = this.formData.remark.length

			uni.showToast({
				title: '测试数据已填充',
				icon: 'success'
			})
		}
	}
}
</script>

<style lang="less">
.font-num {
	color: #999;
	font-size: 28upx;
	text-align: right;
	display: block;
}

.my-content {
	width: 100%;
	padding: 30upx;
	box-sizing: border-box;

	.form-box {
		width: 100%;
		border-radius: 16upx;
		box-shadow: 0px 8px 20px 0px rgba(0, 0, 0, 0.3);
		margin-bottom: 20upx;
		padding: 30upx;
		box-sizing: border-box;
		position: relative;

		.mt20 {
			margin-top: 40upx;
		}

		.add-btn {
			position: absolute;
			color: #3662EC;
			font-size: 60upx;
			top: 0;
			right: 20upx;
		}

		.minus-btn {
			position: absolute;
			font-size: 90upx;
			top: -30upx;
			right: 20upx;
			color: #FA5151;
		}

		.form-title {
			font-size: 36upx;
			color: #000;
			font-weight: 700;
			display: block;
		}

		.ava-img {
			width: 200upx;
			height: 200upx;
			border-radius: 16upx;
			background: #D8D8D8;
			margin: 0 auto;
			overflow: hidden;
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;

			text {
				font-size: 100upx;
				color: #A6A6A6;
				line-height: 100upx;
				display: block;
			}

			image {
				width: 100%;
				height: auto;
				display: block;
				position: absolute;
				top: 0;
				left: 0;
			}
		}

		.form-item {
			margin: 20upx 0;
			font-size: 32upx;

			.blue {
				color: #3662EC;
			}
		}

		.img-list {
			width: 100%;
			display: flex;
			align-items: center;
			margin: 20upx 0 5upx 0;

			.img-add {
				width: 120upx;
				height: 120upx;
				border-radius: 8upx;
				background: #F1F1F1;

				text {
					font-size: 60upx;
					color: #A6A6A6;
					line-height: 120upx;
					text-align: center;
					display: block;
				}
			}

			.img-item {
				width: 120upx;
				height: 120upx;
				border-radius: 8upx;
				overflow: hidden;
				margin-left: 15upx;

				image {
					width: 100%;
					height: auto;
					display: block;
				}
			}
		}

		.num-box {
			display: block;
			width: 100%;
			text-align: right;
			font-size: 32upx;
			color: #A6A6A6;
		}
	}

	.submit {
		width: 100%;
		height: 80upx;
		border-radius: 16upx;
		background: #FF8F1F;
		box-shadow: 0px 8px 20px 0px rgba(0, 0, 0, 0.3);
		color: #fff;
		line-height: 80upx;
		font-size: 44upx;
		font-weight: 700;
		margin-top: 40upx;
	}

	// 模态窗口样式
	.popup-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
		z-index: 999;
		display: flex;
		align-items: center;
		justify-content: center;

		.popup-content {
			width: 90%;
			background: #fff;
			border-radius: 16upx;
			overflow: hidden;

			.map-dialog {
				width: 100%;

				.dialog-header {
					height: 88upx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					padding: 0 30upx;
					border-bottom: 1px solid #eee;

					.title {
						font-size: 32upx;
						font-weight: 500;
						color: #333;
					}

					.close {
						font-size: 48upx;
						color: #999;
						padding: 0 20upx;
					}
				}

				.map {
					width: 100%;
					height: 600upx;
				}

				.dialog-footer {
					padding: 20upx 30upx;
					display: flex;
					justify-content: space-between;
					gap: 20upx;

					.btn {
						flex: 1;
						height: 80upx;
						border-radius: 8upx;
						font-size: 32upx;
						font-weight: 500;
						line-height: 80upx;
					}

					.cancel-btn {
						background: #F5F5F5;
						color: #666;
					}

					.confirm-btn {
						background: #3662EC;
						color: #fff;
					}
				}
			}
		}
	}

	.test-btn {
		width: 100%;
		height: 80upx;
		border-radius: 16upx;
		background: #3662EC;
		color: #fff;
		line-height: 80upx;
		font-size: 32upx;
		text-align: center;
		margin-bottom: 20upx;
		box-shadow: 0px 8px 20px 0px rgba(0, 0, 0, 0.3);
	}
}
</style>